using System.Web;
using System.Web.Security;
using SpiderMaster.AspNet.MemberManagement;

namespace SpiderMaster.AspNet.TradingSystem
{
    public sealed partial class TradingCenterMember
    {
        /// <summary> Creates the member.
        /// </summary>
        /// <param name="UserName">Name of the user.</param>
        /// <param name="AspApplicationName">Name of the ASP application.</param>
        /// <returns></returns>
        public static TradingCenterMember Create(string UserName, string Password, string EmailAddress, string FirstName, string LastName)
        {
            bool imported = (Password.IsNullOrEmpty() || Password == MemberManagement.DefaultValues.PasswordHidden);

            TradingCenterProfileCommon tcpc = TradingCenterProfileCommon.GetProfile(UserName);

            if (imported || (tcpc.MemberId == DefaultValues.IdNullValue) || MemberManagement.DB.Get.Profile(UserName).IsNull() || (tcpc.MemberId != MemberManagement.DB.Get.Profile(UserName).Id))
                tcpc.MemberId = MemberManagement.DB.Insert.NewMember(UserName); // TODO: THROW IF USER EXISTS

            if (FirstName.IsNotNullOrEmpty())
                tcpc.FirstName = FirstName;

            if (LastName.IsNotNullOrEmpty())
                tcpc.LastName = LastName;

            tcpc.Save();

            // All users are added to Guests role upon registration.
            if (!RoleManagement.IsUserInRole(UserName, PredefinedRole.Guest))
                RoleManagement.Current.AddUserToRole(UserName, PredefinedRole.Guest);

            if (RoleManagement.GetUsersInRole(PredefinedRole.GeneralAdministrator).Length == 0)
                if (!RoleManagement.IsUserInRole(UserName, PredefinedRole.GeneralAdministrator))
                    RoleManagement.Current.AddUserToRole(UserName, PredefinedRole.GeneralAdministrator);

            if (HttpContext.Current.Request.IsLocal)
                return TradingCenterMember.GetMember(UserName);

            // Everything that follows is for production site only!
            // Also if the user is AspNet Membership Registered but its there first
            // time as a Trading Center Member then we do not need to send them an activation email.
            MembershipUser mu = Membership.GetUser(UserName);

            if (EmailManagerOld.Helper.Send.WelcomeEmail(UserName, FirstName, Password, tcpc.MemberId, EmailAddress, (MemberManagement.Current.RequireRegistrationEmailActivation ? !imported : false)))
                if (!imported && MemberManagement.Current.RequireRegistrationEmailActivation)
                    Member.LockOut(mu, true);

            MemberManagement.SendMemberNotification(UserName, mu.IsApproved, imported, tcpc.MemberId);

            return TradingCenterMember.GetMember(UserName);
        }

        //    /// <summary> Creates the new full membership.
        //    /// </summary>
        //    /// <param name="Password">The password.</param>
        //    /// <returns></returns>
        //    public TradingCenterMember CreateNewFullMembership(string Password)
        //    { return CreateNewFullMembership(Password, false); }

        //    /// <summary> Creates the new full membership.
        //    /// </summary>
        //    /// <param name="Password">The password.</param>
        //    /// <param name="ForceLocalEmail">if set to <c>true</c> [force local email].</param>
        //    /// <returns></returns>
        //    public TradingCenterMember CreateNewFullMembership(string Password, bool ForceLocalEmail)
        //    {
        //        // TODO:
        //        //if (!LinkManager.DoesUrlContain(VirtualPage.MemberRegister))
        //        //    throw new NotImplementedException("Member Creation Failed. The Page was not recognized as a valid User Registration Page");

        //        //this.SecurityEnabled = true;
        //        //// Must Create Debit Account. This is where we find our MEMBER ID
        //        //this.ProfileCommon.MemberId = MemberManagement.CreateNew(AspNetMembership.UserName);
        //        //this.Password = Password;

        //        int TradingCenterMemberId = MemberManagement.DB.Insert.NewMember(this.ProfileCommon.MemberId, this.AspNetMembership.UserName);

        //        if (ProfileCommon.MemberId != TradingCenterMemberId)
        //            throw new InvalidOperationException("The MemberIds for the 'Community' DataBase compared to the returned result of the 'Trading Center' DataBase did not Match.");
        //        // Save after we have the member Id.
        //        this.ProfileCommon.Save();

        //        AspNetMembership = Membership.GetUser(ProfileCommon.UserName);

        //        //// All users are added to TradingCenter.Guests role upon registration. //
        //        //RoleManagement.AddUserToRole(ProfileCommon.UserName, PredefinedRole.Guest);
        //        //AspNetMembership.IsApproved = !MemberManagement.CurrentSettings.EmailVerificationRequired;

        //        //// TODO: This should be put into Task Manager
        //        //string EmailFirstName = ProfileCommon.FirstName;
        //        //if (string.IsNullOrEmpty(EmailFirstName))
        //        //    EmailFirstName = DefaultValues.NotApplicableText;

        //        //// TODO: Develop some Debugging Switchs i dont like this param on this method.
        //        //bool SendEmail = !HttpContext.Current.Request.IsLocal;
        //        //if (ForceLocalEmail)
        //        //    SendEmail = true;

        //        //if (SendEmail)
        //        //    EmailManagerOld.Helper.Send.WelcomeEmail(ProfileCommon.UserName, EmailFirstName, Password, ProfileCommon.MemberId, AspNetMembership.Email, MemberManagement.CurrentSettings.EmailVerificationRequired);

        //        Membership.UpdateUser(AspNetMembership); // Must Update User //
        //        //// Must set up notification to TradingCenter.GeneralAdministrator of new regerstration
        //        MembershipCreated = true;

        //        return this;
        //    }
    }
}